<template>
  <a-spin :spinning="loading">
    <custom-form ref="form" class="form-wrapper" :is-validate="true" :edit-model="''" :form="form" :form-list="formOption" @change="handleChange" />
    <div class="btn-wrapper">
      <a-button type="primary" :disabled="cannotAdd" @click="handleAdd" v-btnPermission="'bm_047_add_02'">新增临时科目</a-button>
      <a-button :disabled="cannotDelete" @click="handleDelete" v-btnPermission="'bm_047_del_03'">删除临时科目</a-button>
      <a-button type="primary" :disabled="this.data.length === 0" @click="setSecondaryAccount">
        展示二级科目
      </a-button>
      <!-- <a-button
            type="primary"
            :disabled="loading"
            @click="$refs.table.clearTreeExpand()"
          >
            收起全部
          </a-button> -->
      <a-input-search v-model="search" placeholder="请搜索" />
    </div>
    <div class="table-wrapper">
      <u-table
        ref="table"
        fixed-columns-roll
        :height="height"
        show-header-overflow
        default-expand-all
        :tree-config="{
          children: 'children',
          expandAll: false
        }"
        row-id="id"
        :use-virtual="true"
        border
        :row-height="40"
        @row-click="handleRowClick"
      >
        <u-table-column v-for="item in columns" :key="item.dataIndex" :prop="item.dataIndex" :label="item.title" :width="item.width" :fixed="item.fixed" :tree-node="item.dataIndex === 'name'" align="left">
          <template v-slot="{ row }">
            <template v-if="item.dataIndex === 'name'">
              <!-- 搜索时显示结果 -->
              <p v-if="row.projectNameLabel.length > 0" class="cell-text" v-html="row.projectNameLabel.join(`<b>${searchText}</b>`)" :title="row[item.dataIndex]"></p>
              <!-- 普通时 -->
              <p v-else :title="row[item.dataIndex]" :class="row.isEnabled * 1 !== 1 ? 'newIsEnabled' : ''">{{ row.name }}</p>
            </template>
            <template v-else-if="item.dataIndex === 'code'">
              <!-- 搜索时显示结果 -->
              <p v-if="row.costAccountCodeLabel.length > 0" class="cell-text" v-html="row.costAccountCodeLabel.join(`<b>${searchText}</b>`)" :title="row[item.dataIndex]"></p>
              <!-- 普通时 -->
              <p v-else :title="row[item.dataIndex]">{{ row.code }}</p>
            </template>
            <p v-else :title="row[item.dataIndex]">{{ row[item.dataIndex] }}</p>
          </template>
        </u-table-column>
      </u-table>
    </div>
    <base-modal :visible="visible" title="新增临时科目" destroy-on-close :width="900" okText="提交" @cancel="cancel" @ok="handleAddModel">
      <a-spin :spinning="loading2">
        <a-form-model :model="form1" ref="form1" :label-col="{ span: 5 }" :wrapper-col="{ span: 8 }">
          <a-form-model-item v-for="(item, index) in formOption1" :key="index" :prop="item.keyName" :label="item.label" :rules="item.rules">
            <a-input v-model="form1[item.keyName]" :required="true" style="width: 300px;" />
          </a-form-model-item>
        </a-form-model>
        <!-- <custom-form ref="form1" :is-validate="true" :edit-model="''" :rules="rules" :form="form1" :form-list="formOption1" /> -->
      </a-spin>
    </base-modal>
  </a-spin>
</template>
<script>
import { UTable, UTableColumn } from 'umy-ui'
import BaseModal from '@/components/BaseModal'
import { formOption, columns, formOption1 } from './model.js'
import debounce from 'lodash/debounce'
import { isHideQuote, updateQuote } from '@/api/businessAffairs/updateInformation'
import { getCostPlan, addProjectTree, deleteProjectTreeById } from '@/api/businessAffairs/costAccountInit'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
export default {
  name: 'CostAccountInit',
  extends: new BaseEditPage(),
  props: {
    resData: {
      type: Object
    },
    id: {
      type: String
    }
  },
  components: {
    UTable,
    UTableColumn,
    BaseModal
  },
  data() {
    return {
      // 表单
      form: {
        quote: 0
      },
      // 表单配置
      formOption,
      // 搜索文本
      search: '',
      // 搜索文本显示值
      searchText: '',
      // 表头
      columns,
      // 表格高度
      height: 0,
      // 不能添加
      cannotAdd: true,
      // 不能删除
      cannotDelete: true,
      // 表格数据
      data: [],
      // 表格数据映射
      dataMap: new Map(),
      // 搜索展开项
      expandMap: new Map(),
      // 弹框隐藏显示
      visible: false,
      // 新增表单
      form1: {},
      // 新增表单配置
      formOption1,
      loading: false, // 加载控件
      loading2: false,
      projectId: this.$userInfo().currentPost.projectId, //当前项目
      isShowPopup: false, //是否显示弹框
      selectRow: {}, //选中行数据
      editModel: 0, // 操作状态:1查看;2编辑
      isClickBtn: false //是否点击科目按钮
    }
  },
  computed: {
    // 新增表单校验
    rules() {
      const obj = {}
      formOption1.forEach(item => {
        if (item.rules) {
          obj[item.keyName] = item.rules
        }
      })
      return obj
    }
  },
  watch: {
    search: {
      handler() {
        this.searchChange()
      }
    },
    visible: {
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.$checkRequireItem()
          })
        }
      }
    },
    resData: {
      handler(val) {
        if (val) {
          this.data = val?.trees || []
          this.form.quote = val?.quote
          this.flattenTree(this.data)
          this.$nextTick(() => {
            this.reloadData(this.data)
          })
          this.projectId && this.init()
        }
      }
    }
  },
  mounted() {
    this.height = document.querySelector('.table-wrapper').offsetHeight + 100
  },
  methods: {
    //展开二级科目
    setSecondaryAccount() {
      this.$emit('getDetailFn', false)
      this.isClickBtn = true
      // this.$refs.table.setAllTreeExpansion()
    },
    /**
     * @description: 新增
     * @return {void}
     */
    handleAdd() {
      this.visible = true
    },
    //关闭
    cancel() {
      this.form1.projectFormat = null
      this.visible = false
    },
    /**
     * @description: 提交
     * @return {void}
     */
    handleAddModel() {
      let parms = {
        id: this.selectRow.id
      }
      this.loading2 = true
          parms.name = this.form1.projectFormat
          addProjectTree(parms)
            .then(res => {
              if (res.data.code == '0') {
                this.$message.success('新增成功')
                this.form1.projectFormat = null
                this.cannotAdd = true
                this.cannotDelete = true
                this.$emit('getDetailFn')
                this.visible = false
              }
              this.loading2 = false
            })
            .catch(err => {
              this.loading2 = false
              this.$message.warning(err.msg)
            })
      return
      this.$refs.form1.validate(valid => {
        if (valid) {
          this.loading2 = true
          parms.name = this.form1.projectFormat
          addProjectTree(parms)
            .then(res => {
              if (res.data.code == '0') {
                this.$message.success('新增成功')
                this.form1.projectFormat = null
                this.cannotAdd = true
                this.cannotDelete = true
                this.$emit('getDetailFn')
                this.visible = false
              }
              this.loading2 = false
            })
            .catch(err => {
              this.loading2 = false
              this.$message.warning(err.msg)
            })
        }
      })
    },
    /**
     * @description: 删除
     * @return {void}
     */
    handleDelete() {
      let _that = this
      this.$confirm({
        title: '确定是否删除？',
        content: '删除该内容后，将不可找回。',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          _that.loading = true
          return deleteProjectTreeById({ id: _that.selectRow.id })
            .then(res => {
              if (res.data?.code == '0') {
                _that.$message.success('删除成功！')
                _that.$emit('getDetailFn')
                _that.cannotAdd = true
                _that.cannotDelete = true
                _that.loading = false
              }
            })
            .catch(res => {
              _that.loading = false
            })
        }
      })
    },
    async handleChange() {
      let _that = this
      await _that.updateQuoteFn()
      this.$emit('changeGetData')
    },
    /**
     * @description: 保存并查询项目成本归集树
     * @param {function}
     * @return {void}
     */
    updateQuoteFn() {
      this.loading = true
      let req = {
        id: this.id,
        quote: this.form.quote
      }
      return updateQuote(req)
        .then(res => {
          this.loading = false
        })
        .catch(err => {
          this.loading = false
        })
    },
    /**
     * @description: 搜索函数防抖
     * @param {function}
     * @return {void}
     */
    searchChange: debounce(function() {
      this.handleSearch()
    }, 500),
    /**
     * @description: 查找父级节点
     * @return {void}
     */
    findParent(map) {
      const p = new Map()
      for (const value of map.values()) {
        if (this.dataMap.has(value?.parentId) && !this.expandMap.has(value.parentId)) {
          this.expandMap.set(value.parentId, this.dataMap.get(value.parentId))
          p.set(value.parentId, this.dataMap.get(value.parentId))
        }
      }
      if (p.size > 0) {
        this.findParent(p)
      }
    },
    /**
     * @description: 搜索
     * @return {void}
     */
    handleSearch() {
      this.searchText = this.search
      // 清除展开项
      this.expandMap.clear()
      this.$refs.table.clearTreeExpand()
      for (const value of this.dataMap.values()) {
        if ((this.search ?? '') === '') {
          value.projectNameLabel = []
          value.costAccountCodeLabel = []
        } else {
          if (value?.name.includes(this.search)) {
            value.projectNameLabel = value.name.split(this.search)
            if (this.dataMap.has(value?.parentId) && !this.expandMap.has(value.parentId)) {
              this.expandMap.set(value.parentId, this.dataMap.get(value.parentId))
            }
          } else {
            value.projectNameLabel = []
          }
          if (value?.code.includes(this.search)) {
            value.costAccountCodeLabel = value.code.split(this.search)
            if (this.dataMap.has(value?.parentId) && !this.expandMap.has(value.parentId)) {
              this.expandMap.set(value.parentId, this.dataMap.get(value.parentId))
            }
          } else {
            value.costAccountCodeLabel = []
          }
        }
      }
      this.findParent(this.expandMap)
      this.reloadData(this.data)
    },
    /**
     * @description: 扁平化树
     * @param {array} tree 树
     * @return {void}
     */
    flattenTree(tree, index = 0) {
      for (let i = 0; i < tree.length; i++) {
        tree[i].projectNameLabel = []
        tree[i].costAccountCodeLabel = []
        tree[i].sortExpandIndex = index
        index++
        this.dataMap.set(tree[i].id, tree[i])
        if (tree[i]?.children && tree[i].children?.length > 0) {
          this.flattenTree(tree[i].children, index)
        }
      }
    },
    //设置展示二级科目
    setSecondary(data) {
      if (data && data.length) {
        data.forEach(item => {
          if (item.isShow) {
            this.$refs.table.setTreeExpansion(item, true)
          }
          if (item.children && item.children.length) {
            this.setSecondary(item.children)
          } else {
            item.children = null
          }
        })
      }
      return data
    },
    /**
     * @description: 加载数据
     * @param {array} data
     * @return {void}
     */
    reloadData(data) {
      // 获取之前展开数据
      const expandRecords = this.$refs.table.getTreeExpandRecords()
      // 获取之前滚动高度(表格实例上的scrollTop属性，在滚动到底部时会小于真实的scrollTop值，因此直接从dom获取真实滚动高度)
      const scrollTop = this.$refs.table.tableExample().bodyWrapper.scrollTop
      const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
      // 加载数据
      this.$refs.table.reloadData(data).then(() => {
        // 数据加载完成
        if (this.expandMap.size > 0) {
          // 展开搜索项
          Array.from(this.expandMap)
            .sort((a, b) => a[1].sortExpandIndex - b[1].sortExpandIndex)
            .forEach(row => {
              this.$refs.table.setTreeExpansion(row[1], true)
            })
        } else {
          if (!this.isClickBtn) {
            // 展开之前的展开行
            expandRecords.forEach(row => {
              this.$refs.table.setTreeExpansion(row, true)
            })
          } else {
            this.setSecondary(data)
          }
        }

        this.$refs.table.pagingScrollTopLeft(scrollTop, scrollLeft)
      })
    },

    /**
     * @description: 表格行点击
     * @param {object} row 行数据
     * @param {object} column 表头对象
     * @param {event} event 事件对象
     * @return {void}
     */
    handleRowClick(row, column, event) {
      this.cannotAdd = !(row.level === 2) || (row.level === 2 && (row.name == '增值税附加' || row.name == '管理费（含规费）'))
      this.cannotDelete = row?.isEnabled === 1
      this.selectRow = row
    },
    //是否隐藏引用
    getHandleAddModel(req) {
      this.loading = true
      isHideQuote(req)
        .then(res => {
          this.loading = false
          if (res.code == '0') {
            this.formOption[0].hidden = res.data
            this.loading = false
          }
        })
        .catch(err => {
          this.loading = false
        })
    },

    init() {
      let req = {
        projectId: this.projectId
      }
      this.getHandleAddModel(req)
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
@{deep} .ant-form {
  margin-bottom: 16px;
  width: 682px;
  .ant-row-flex {
    // height: 32px;
    .ant-col {
      height: 32px;
    }
    .ant-col:nth-of-type(1) .ant-form-item-label {
      text-align: left;
    }
  }
}
.btn-wrapper {
  display: flex;
  width: 682px;
  margin-bottom: 16px;
  margin-top: 25px;
  @{deep} .ant-btn {
    margin-right: 16px;
  }
  @{deep} .ant-input-search > .ant-input {
    height: 100%;
  }
}
.table-wrapper {
  height: calc(100% - 96px);
  width: 682px;
}
@{deep} .cell-text {
  b {
    font-weight: normal;
    color: red;
  }
}
@{deep} .ant-spin-container {
  height: 100%;
}
.newIsEnabled {
  // color:#1890ff;
}
</style>
